

package com.dog.basics.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.sys.AdminSysMenuAddDto;
import com.dog.basics.bean.dto.admin.sys.AdminSysMenuEditDto;
import com.dog.basics.bean.vo.admin.sys.MenuTree;
import com.dog.basics.bean.vo.admin.sys.TreeUtil;
import com.dog.basics.bean.model.sys.SysMenu;
import com.dog.basics.bean.model.sys.SysRoleMenu;
import com.dog.basics.bean.vo.admin.sys.AdminMenuVO;
import com.dog.basics.common.constant.CacheConstants;
import com.dog.basics.common.constant.CommonConstants;
import com.dog.basics.common.constant.enums.MenuTypeEnum;
import com.dog.basics.dao.sys.SysMenuMapper;
import com.dog.basics.dao.sys.SysRoleMenuMapper;
import com.dog.basics.service.sys.SysMenuService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author guonh
 * @since 2017-10-29
 */
@Service
@AllArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    private final SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    @Cacheable(value = CacheConstants.MENU_DETAILS, key = "#roleId", unless = "#result.isEmpty()")
    public List<AdminMenuVO> findMenuByRoleId(Long roleId) {
        return baseMapper.listMenusByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
    public Boolean removeMenuById(Long id) {
        // 查询父节点为当前节点的节点
        List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query().lambda().eq(SysMenu::getParentId, id));
        Validator.validateFalse(CollUtil.isNotEmpty(menuList), "菜单含有下级不能删除");
  /*      if (CollUtil.isNotEmpty(menuList)) {
            return R.failed("菜单含有下级不能删除");
        }
*/
        //先判断有没有
        List<SysRoleMenu> list=sysRoleMenuMapper.selectList(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getMenuId, id));
        if(CollUtil.isNotEmpty(list)){
            Validator.validateTrue(retBool(sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getMenuId, id))), "common.del");
        }
        // 删除当前菜单及其子菜单
        Validator.validateTrue(this.removeById(id), "common.del");
        return Boolean.TRUE;
    }

    @Override
    @CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
    public Boolean updateMenuById(SysMenu sysMenu) {
        return this.updateById(sysMenu);
    }

    /**
     * 构建树查询 1. 不是懒加载情况，查询全部 2. 是懒加载，根据parentId 查询 2.1 父节点为空，则查询ID -1
     *
     * @param lazy     是否是懒加载
     * @param parentId 父节点ID
     * @return
     */
    @Override
    public List<MenuTree> treeMenu(boolean lazy, Long parentId) {
        if (!lazy) {
            return TreeUtil.buildTree(
                    baseMapper.selectList(Wrappers.<SysMenu>lambdaQuery().orderByAsc(SysMenu::getSort)),
                    CommonConstants.MENU_TREE_ROOT_ID);
        }

        Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
        return TreeUtil.buildTree(
                baseMapper.selectList(
                        Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getParentId, parent).orderByAsc(SysMenu::getSort)),
                parent);
    }

    /**
     * 查询菜单
     *
     * @param all      全部菜单
     * @param type     类型
     * @param parentId 父节点ID
     * @return
     */
    @Override
    public List<MenuTree> filterMenu(Set<AdminMenuVO> all, String type, Long parentId) {
        List<MenuTree> menuTreeList = all.stream().filter(menuTypePredicate(type)).map(MenuTree::new)
                .sorted(Comparator.comparingInt(MenuTree::getSort)).collect(Collectors.toList());
        Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
        return TreeUtil.build(menuTreeList, parent);
    }

    /**
     * menu 类型断言
     *
     * @param type 类型
     * @return Predicate
     */
    private Predicate<AdminMenuVO> menuTypePredicate(String type) {
        return vo -> {
            if (MenuTypeEnum.TOP_MENU.getDescription().equals(type)) {
                return MenuTypeEnum.TOP_MENU.getType().equals(vo.getType());
            }
            // 其他查询 左侧 + 顶部
            return !MenuTypeEnum.BUTTON.getType().equals(vo.getType());
        };
    }
    /**
     * @Description: 查看菜单详情
     * @Param: obj
     * @return: Boolean
     * @Author: cy
     * @Date: 2020/05/19  0027
     */
    /**
     * @Description: 修改
     * @Param: obj
     * @return: Boolean
     * @Author: cy
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminMenuVO getObjXq(Long id) {
        SysMenu dogNews = this.getById(id);
        Validator.validateNotNull(dogNews, "common.noData");
        AdminMenuVO menuVO = new AdminMenuVO();
        BeanUtil.copyProperties(dogNews, menuVO);
        return menuVO;
    }

    /**
     * @Description: 增加
     * @Param: obj
     * @return: Boolean
     * @Author: cy
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAdminObj(AdminSysMenuAddDto obj) {
        SysMenu dogNews = new SysMenu();
        BeanUtil.copyProperties(obj, dogNews);
        dogNews.setCreateTime(DateUtil.currentSeconds());
        Validator.validateTrue(this.save(dogNews), "common.save");
        return Boolean.TRUE;
    }


    /**
     * @Description: 修改
     * @Param: obj
     * @return: Boolean
     * @Author: cy
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editAdminObj(AdminSysMenuEditDto obj) {
        SysMenu dogNews = this.getById(obj.getMenuId());
        Validator.validateNotNull(dogNews, "common.noData");
        BeanUtil.copyProperties(obj, dogNews);
        dogNews.setUpdateTime(DateUtil.currentSeconds());
        Validator.validateTrue(this.updateById(dogNews), "common.edit");
        return Boolean.TRUE;
    }

}
